package com.zlzvip.android.common.web;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.Keep;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.cncn.youmengsharelib.ShareData;
import com.pachong.android.frameworkbase.utils.AppUtil;
import com.pachong.android.frameworkbase.utils.NetUtil;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.zlzvip.android.common.pay.PayReceiver;
import com.zlzvip.android.common.pay.PayReceiverFail;
import com.zlzvip.android.common.pay.PayResultCallback;
import com.zlzvip.android.wxapi.WXPayEntryActivity;

/**
 * Created by Zoi.
 * E-mail：KyluZoi@gmail.com
 * 2016/7/28
 * 移动端接口的实现类
 */
public class MobileFunImpl implements MobileImpable {
    private CommonWebviewFragment mFragment;
    private IWXAPI msgApi;
    private PayReceiverFail payReceiverFail;
//    private PayTask alipay;
    public static PayReceiver payReceiver;


    public MobileFunImpl(CommonWebviewFragment fragment) {
        mFragment = fragment;
        initPay();
    }

    private void initPay() {

        msgApi = WXAPIFactory.createWXAPI(getContext(), null);
        //将该app注册到微信
        String wetharAppid = WXPayEntryActivity.WETHAR_APPID;
        msgApi.registerApp(wetharAppid);
//        alipay = new PayTask(mFragment.getActivity());
        //支付成功的回调
        payReceiver= new PayReceiver(new PayResultCallback() {
            @Override
            public void onSuccess() {
//
                mFragment.getWebview().loadUrl("javascript:onPayResult(0)");
            }
            @Override
            public void onFail() {
                mFragment.getWebview().loadUrl("javascript:onPayResult(1)");
            }
        });
        getContext().registerReceiver(payReceiver, new IntentFilter(WXPayEntryActivity.WECHAR_PAY));

        //支付失败的回调
        payReceiverFail= new PayReceiverFail(new PayResultCallback() {
            @Override
            public void onSuccess() {
                mFragment.getWebview().loadUrl("javascript:onPayResult(1)");
            }
            @Override
            public void onFail() {
                mFragment.getWebview().loadUrl("javascript:onPayResult(1)");
            }
        });
        getContext().registerReceiver(payReceiverFail, new IntentFilter(WXPayEntryActivity.WECHAR_PAY_FAIL));
    }

    @Keep
    @JavascriptInterface
    @Override
    public String getTokenInfo() {
        String token = null;
       /* if (AccountManager.isTokenValid()) {
            TokenInfo tokenInfo = AccountManager.getTokenInfo();
            token = GsonUtils.toJson(tokenInfo);
        }*/
        return token;
    }

    @Keep
    @JavascriptInterface
    @Override
    public void login() {
        Log.d("kyluzoi", "web use login");
    }

    @Keep
    @JavascriptInterface
    @Override
    public void pay(String partnerId, String prepayId, String package1, String nonceStr, String timeStamp, String sign) {
//        EasyToast.showToast(mFragment.getContext(),"微信支付暂未开放");
        boolean sIsWXAppInstalledAndSupported = msgApi.isWXAppInstalled()
                && msgApi.isWXAppSupportAPI(); // 判断微信是否安装
        if (!sIsWXAppInstalledAndSupported) {
            Toast.makeText(getContext(), "未安装微信", Toast.LENGTH_SHORT).show();
        } else {
            onStartWechatPay(partnerId, prepayId, package1, nonceStr,timeStamp, sign);
//            getWechatPayInfo(orderNum);
        }
    }

    private void onStartWechatPay(String partnerId, String prepayId, String package1, String nonceStr, String timeStamp, String sign) {
        PayReq request = new PayReq();
        //微信分配的公众账号ID
        request.appId = WXPayEntryActivity.WETHAR_APPID;
        //微信支付分配的商户号
        request.partnerId = partnerId;
        //微信返回的支付交易会话ID
        request.prepayId =  prepayId;
        //暂填写固定值Sign=WXPay
        request.packageValue = package1;
        //随机字符串，不长于32位。推荐随机数生成算法
        request.nonceStr = nonceStr;
        //时间戳，请见接口规则-参数规定
        request.timeStamp = timeStamp;
        //签名，详见签名生成算法
        request.sign = sign;
        msgApi.sendReq(request);
    }


    @Keep
    @JavascriptInterface
    @Override
    public void uploadImage(String tag) {
        Log.d("kyluzoi", "web use uploadimage");
        /*PhotoAlertFragment photoAlertFragment = new PhotoAlertFragment();
        photoAlertFragment.show(getActivity().getFragmentManager(), "tag");
        photoAlertFragment.setOnCitySelectedListener(this);
        mSynTag = tag;*/
    }

    @Keep
    @JavascriptInterface
    @Override
    public void showToast(String url) {
//        return mConnectable.callback();
    }

    @Keep
    @JavascriptInterface
    @Override
    public void share(String title, String content, String imgUrl, String targetUrl) {
        Log.d("kyluzoi", "web use share");
        ShareData shareInfo = new ShareData(imgUrl, title, content, targetUrl);
        if (TextUtils.isEmpty(shareInfo.getImageUrl())) {
            shareInfo.setImageUrl("http://baidu.com");
        }
//      ShareHelper.share(getActivity(), MySharePlatformActivity.class, shareInfo, new MyShareListener());
//        ShareHelper.share(getActivity(), MySharePlatformActivity.class, shareInfo, new MyShareListener());
    }

    @Keep
    @JavascriptInterface
    @Override
    public void back() {
        mFragment.getActivity().finish();
    }

    @Keep
    @JavascriptInterface
    @Override
    public void showTabBar() {
    }

    @Keep
    @JavascriptInterface
    @Override
    public void hideTabBar() {
    }

    @Keep
    @JavascriptInterface
    @Override
    public boolean netIsAvalible() {
        return NetUtil.isAvalible(mFragment.getActivity());
    }

    @Keep
    @JavascriptInterface
    @Override
    public int getVersionCode() {
        return AppUtil.getVersionCode(mFragment.getActivity());
    }




    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }
    private Context getContext() {
        return mFragment.getContext();
    }


}
